from flask import Flask, request
from flask_sse import sse
import json
import requests

app = Flask(__name__)
# Redis 配置
REDIS_PASSWORD = "123456"
app.config["REDIS_URL"] = f"redis://:{REDIS_PASSWORD}@localhost"  # 添加密码认证
app.register_blueprint(sse, url_prefix='/stream')

# proxy_main 的 URL
PROXY_MAIN_URL = "http://0.0.0.0:8080/execute"


@app.route('/sse', methods=['POST'])
def receive_message():
    """接收来自代理服务的消息并推送给客户端"""
    data = request.json
    client_id = data.get('client_id')
    command = data.get('command')
    params = data.get('params', {})

    if not command:
        return json.dumps({'error': 'Missing command'}), 400

    # 发送请求到 proxy_main（unionpay-mcp-server）
    try:
        response = requests.post(PROXY_MAIN_URL, json={"command": command, "params": params})
        response_data = response.json()
        print(response_data)

        if 'result' in response_data:
            # 发送消息到特定客户端或所有订阅者
            sse.publish({"message": response_data['result']}, type='mcp-update', channel=client_id)
            return json.dumps({'status': 'success', 'result': response_data['result']}), 200
        else:
            return json.dumps({'error': 'No result in response'}), 500
    except Exception as e:
        print(e)
        return json.dumps({'error': str(e)}), 500


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=50000)
